package com.atguigu.flink0922.chapter05.transform;

import com.atguigu.flink0922.bean.WaterSensor;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

import java.util.ArrayList;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/3/3 9:07
 */
public class Flink10_Process_KeyBy_Pre {
    public static void main(String[] args) {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(2);
        // select id, 常量, 聚合函数   from .. group by id
        ArrayList<WaterSensor> waterSensors = new ArrayList<>();
        waterSensors.add(new WaterSensor("sensor_1", 1607527992000L, 20));
        waterSensors.add(new WaterSensor("sensor_1", 1607527994000L, 50));
        waterSensors.add(new WaterSensor("sensor_1", 1607527996000L, 30));
        waterSensors.add(new WaterSensor("sensor_2", 1607527993000L, 10));
        waterSensors.add(new WaterSensor("sensor_2", 1607527995000L, 30));
        
        // 统计每个传感器的水位和!
        env
            .fromCollection(waterSensors)
            .process(new ProcessFunction<WaterSensor, Integer>() {
                int sum = 0;
                
                @Override
                public void processElement(WaterSensor value,
                                           Context ctx,
                                           Collector<Integer> out) throws Exception {
                    sum += value.getVc();
                    out.collect(sum);
                }
            })
            .print();
        
        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
